from PyQt6.QtCore import QObject
from ..model.tcp_client import TcpClientModel
from ..view.gui import ClientGUI
from ..view.interfaces import IClientView
from utils.exceptions import ConnectionError, SendDataError

class ClientPresenter(QObject):
    """客户端协调器"""
    def __init__(self, view: IClientView):
        super().__init__()
        self.view = view
        self.model = TcpClientModel()

        # 绑定模型信号
        self.model.connected.connect(lambda: self.view.update_connection_status(True))
        self.model.disconnected.connect(lambda: self.view.update_connection_status(False))
        self.model.data_received.connect(self._handle_received_data)
        self.model.error_occurred.connect(self.view.show_error_message)

        # 绑定视图信号
        if isinstance(view, ClientGUI):
            view.connect_btn.clicked.connect(self._connect_to_server)
            view.disconnect_btn.clicked.connect(self.model.disconnect)
            view.send_btn.clicked.connect(self._send_data)

    def _connect_to_server(self):
        """处理连接请求"""
        try:
            host, port = self.view.get_connection_params()
            self.model.connect_to_server(host, port)
        except ConnectionError as e:
            self.view.show_error_message(str(e))
        except ValueError:
            self.view.show_error_message("端口号必须为整数")

    def _send_data(self):
        """处理数据发送"""
        try:
            data = self.view.get_send_data().encode('utf-8')
            self.model.send_data(data)
            self.view.display_received_data(f"[发送] {data.decode()}")
        except SendDataError as e:
            self.view.show_error_message(str(e))

    def _handle_received_data(self, data: bytes):
        """处理接收数据"""
        try:
            decoded = data.decode('utf-8')
            self.view.display_received_data(decoded)
        except UnicodeDecodeError:
            self.view.show_error_message("收到非UTF-8格式数据")